/*
 * @Author: owen 
 * @Date: 2017-11-30 15:18:04 
 * @Last Modified by: owen
 * @Last Modified time: 2017-11-30 16:53:44
 */

package models

import (
	"github.com/astaxie/beego"
	"encoding/json"
    "fmt"
    "time"
    jwt "github.com/dgrijalva/jwt-go"
)

var key []byte = []byte("kenwei Technology")
const self_file string = "hjwt.go:"

type myTokan struct {
	Tokan string `json:"tokan"`
}


func GenToken()  string{
	tokan := jwt.New(jwt.SigningMethodHS256)
	claims := make(jwt.MapClaims)
	claims["exp"] = time.Now().Add(time.Hour*time.Duration(1)).Unix()
	claims["iat"] = time.Now().Unix()
	tokan.Claims = claims
    tokanString, err := tokan.SignedString(key)
    if err != nil {
        beego.Debug(self_file,err)
        return ""
    }
    resp := myTokan{Tokan:tokanString}
    jresp,err:=json.Marshal(&resp)
    return string(jresp)
}

// 校验token是否有效
func CheckToken(token string) bool {
    _, err := jwt.Parse(token, func(*jwt.Token) (interface{}, error) {
        return key, nil
    })
    if err != nil {
        fmt.Println("parase with claims failed.", err)
        return false
    }
    return true
}